<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24" >
            <a-form-item label="门户名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入门户名称" v-decorator="[ 'portalName',{rules: [{ required: true, message: '请输入门户名称' }]}]"/>
            </a-form-item>
            <a-form-item label="门户类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select v-decorator="[ 'portalType',{rules: [{ required: true, message: '请选择门户类型' }]}]" @change="portalTypeChange" placeholder="请选择门户类型">
                <a-select-option value="enterprisePortal">企业门户</a-select-option>
                <a-select-option value="processPortal">流程门户</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24" >
            <a-form-item label="是否默认" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="radio" v-decorator="['izDefault', {}]" :trigger-change="true" dictCode="yn"/>
              <br/><span style="color:red">注：选择是时，会取消原有已设置默认的门户，将当前门户设为默认</span>
            </a-form-item>
          </a-col>
          <a-col :span="24" >
            <a-form-item label="路由页面" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入路由页面" v-decorator="[ 'url',{rules: [{ required: true, message: '请输入路由页面' }]}]"/>
            </a-form-item>
          </a-col>
          <a-col :span="24" >
            <a-form-item label="模板样式" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <img v-if="portalTypeImg === 'oaPortal' " :src="EoaPotalSiteConfig.oaPortal.imgUrl" width="300px;" height="200px;" preview/>
              <img v-if="portalTypeImg === 'bpmPortal' " :src="EoaPotalSiteConfig.bpmPortal.imgUrl" width="300px;" height="200px;" preview/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="门户网站模块设置" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="eoaPortalSiteSubTable.loading"
          :columns="eoaPortalSiteSubTable.columns"
          :dataSource="eoaPortalSiteSubTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import pick from 'lodash.pick'
  import { httpAction,getAction } from '@/api/manage'
  import { FormTypes,getRefPromise,validateFormAndTables,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JDate from '@/components/jeecg/JDate'
  import { FunctionEnum } from '@/utils/portal/constant'
  import { duplicateCheck } from '@/api/api'
  import { EoaPotalSiteConfig } from './EoaPortalSiteConfig'

  export default {
    name: 'EoaPortalSiteForm',
    mixins: [JEditableTableMixin],
    components: {
      JFormContainer,
      JDate
    },
    data() {
      return {
        FunctionEnum,
        EoaPotalSiteConfig,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          portalName: {
            rules: [
              { required: true, message: '请选择类型!' },
              {validator: this.validateName}
            ]
          },
        },
        refKeys: ['eoaPortalSiteSub', ],
        tableKeys:['eoaPortalSiteSub', ],
        activeKey: 'eoaPortalSiteSub',
        // 门户网站设置子表
        eoaPortalSiteSubTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '模块坐标',
              key: 'name',
              type: FormTypes.select,
              options:[],
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [
                {
                  required: true, // 必填
                  message: '请选择${title}' // 显示的文本
                },
                {
                  unique: true,
                  message: '${title}不能重复'
                }
              ]
            },
            {
              title: '功能',
              key: 'function',
              type: FormTypes.select,
              options:[
                {text:'轮播图',value:'EoaCmsBanner'},
                {text:'新闻动态',value:'EoaCmsNewsInfo'},
                {text:'制度/下载',value:'EoaCmsRuleInfo'},
                {text:'签约新闻',value:'EoaCmsSignNews'},
                {text:'系统公告',value:'EoaCmsUserNotice'},
                {text:'我的计划',value:'EoaCmsPlan'},
                {text:'友情链接',value:'EoaCmsLink'},
                {text:'常用功能',value:'EoaCmsCommUse'},
                {text:'流程中心',value:'EoaCmsMyProcess'},
                {text:'流程提醒',value:'EoaCmsProcessNotice'},
                {text:'我的申请',value:'EoaCmsApplyProcess'},
                {text:'流程数据分析',value:'EoaCmsProcessChatData'},
                {text:'流程类型统计',value:'EoaCmsProcessTypeChat'},
                {text:'近期邮件',value:'EoaCmsEmail'}
              ],
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              validateRules: [
                {
                  required: true, // 必填
                  message: '请选择${title}' // 显示的文本
                },
                {
                  unique: true,
                  message: '${title}不能重复'
                }
              ]
            },
          ]
        },
        url: {
          add: "/eoa/cms/eoaPortalSite/add",
          edit: "/eoa/cms/eoaPortalSite/edit",
          queryById: "/eoa/cms/eoaPortalSite/queryById",
          editIzDefault: "/eoa/cms/eoaPortalSite/editIzDefault",
          eoaPortalSiteSub: {
            list: '/eoa/cms/eoaPortalSite/queryEoaPortalSiteSubByMainId'
          },
        },
        portalTypeImg:''
      }
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：false流程表单 true普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      },
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      portalTypeChange(t){
        if(t === 'enterprisePortal'){
          this.eoaPortalSiteSubTable.columns[0].options = EoaPotalSiteConfig.oaPortal.options;
          this.portalTypeImg = 'oaPortal'
        }else{
          this.eoaPortalSiteSubTable.columns[0].options = EoaPotalSiteConfig.bpmPortal.options;
          this.portalTypeImg = 'bpmPortal'
        }
      },
      validateName(rule, value, callback){
        var params = {
          tableName: "eoa_portal_site",
          fieldName: "portal_name",
          fieldVal: value,
          dataId: this.model.id
        };
        duplicateCheck(params).then((res)=>{
          if(res.success){
            callback();
          }else{
            callback(res.message);
          }
        })
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        let fieldval = pick(this.model,'portalName','url','portalType','izDefault')
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
        if(!this.model.izDefault){
          this.form.setFieldsValue({izDefault:'1'})
        }
        // 加载子表数据
        if (this.model.id) {
          if(this.model.portalType === 'enterprisePortal'){
            this.eoaPortalSiteSubTable.columns[0].options = EoaPotalSiteConfig.oaPortal.options;
            this.portalTypeImg = 'oaPortal'
          }else{
            this.eoaPortalSiteSubTable.columns[0].options = EoaPotalSiteConfig.bpmPortal.options;
            this.portalTypeImg = 'bpmPortal'
          }
          let params = { id: this.model.id }
          if(this.model.dataJson){
            this.eoaPortalSiteSubTable.dataSource = JSON.parse(this.model.dataJson);
          }
        }
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          eoaPortalSiteSubList: allValues.tablesValue[0].values,
        }
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          })
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'portalCode','portalName','dataJson','createBy','createTime','updateBy','updateTime','sysOrgCode','portalType'))
      },
      /** 确定按钮点击事件 */
      handleOk() {
        /** 触发表单验证 */
        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormAndTables(this.form, tables)
        }).then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          return this.request(formData)
        }).catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      },
      /** 发起请求，自动判断是执行新增还是修改操作 */
      request(formData) {
        //处理子表信息
        let dataJson = [];
        for(let item of formData.eoaPortalSiteSubList){
          let json = {
            name:item.name,
            function:item.function,
            path:FunctionEnum[item.function].path,
            formData:FunctionEnum[item.function].formData
          }
          dataJson.push(json)
        }
        formData.dataJson = JSON.stringify(dataJson);
        let url = this.url.add, method = 'post'
        if (this.model.id) {
          url = this.url.edit
          method = 'put'
        }
        this.confirmLoading = true
        httpAction(url, formData, method).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      },

    }
  }
</script>

<style scoped>
</style>